//shmClient.cpp
#include "comm.hpp"

int main()
{
    // 1.创建公共的key
    key_t k = ftok(PATH_NAME, PROJ_ID);
    if (k < 0)
    {
        Log("create key failed", Error) << "client key : " << k << endl;
        exit(1);
    }
    Log("create key success", Debug) << "client key : " << k << endl;

    // 2.获取共享内存
    int shmid = shmget(k, SHM_SIZE, IPC_CREAT);
    if (shmid < 0)
    {
        Log("create shm failed", Error) << "shmid : " << shmid << endl;
        exit(2);
    }
    Log("create shm success", Debug) << "shmid : " << shmid << endl;

    // 3.将指定的共享内存，挂接到自己的地址空间
    char* shmaddr = (char*)shmat(shmid, nullptr, 0);
    if (shmaddr == nullptr)
    {
        Log("attach shm failed", Error) << "shmid : " << shmid << endl;
    }
    Log("attach shm success", Debug) << "shmid : " << shmid << endl;

    // 使用
    // client将共享内存看做一个字符串

    // 通过管道文件实现访问控制
    int fd = OpenFIFO(FIFO_NAME, WRITE);
    while (true)
    {
        ssize_t s = read(0, shmaddr, SHM_SIZE - 1);
        if (s > 0)
        {
            shmaddr[s-1] = 0; // 去掉\n
            Signal(fd);
            if (strcmp(shmaddr, "quit") == 0) break;
        }
    }
    CloseFIFO(fd);

    // while (true)
    // {
    //     ssize_t s = read(0, shmaddr, SHM_SIZE - 1);
    //     if (s > 0)
    //     {
    //         shmaddr[s-1] = 0; // 去掉\n
    //         if (strcmp(shmaddr, "quit") == 0) break;
    //     }
    // }

    // for (int i = 0; i < 5; i++)
    // {
    //     snprintf(shmaddr, SHM_SIZE - 1, "hello I am client, my pid: %d, i = %d\n", getpid(), i);
    //     sleep(1);
    // }
    // strcpy(shmaddr, "quit");

    // 4.将指定的共享内存，从自己的地址空间去关联
    int n = shmdt(shmaddr);
    assert(n != -1);
    Log("detach shm success", Debug) << "shmid : " << shmid << endl;

    // client不用删除共享内存，会由server删除

    return 0;
}